package com.sanyue.codingsettlement.strategy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.exception.BusinessException;
import com.sanyue.codingsettlement.manager.AiManager;
import com.sanyue.codingsettlement.manager.RedisLimiterManager;
import com.sanyue.codingsettlement.model.dto.question.QuestionContent;
import com.sanyue.codingsettlement.model.dto.question.QuestionContentOption;
import com.sanyue.codingsettlement.model.entity.App;
import com.sanyue.codingsettlement.model.entity.Question;
import com.sanyue.codingsettlement.model.entity.UserAnswer;
import com.sanyue.codingsettlement.service.QuestionService;
import com.sanyue.codingsettlement.strategy.ai.AiTestResult;
import com.sanyue.codingsettlement.strategy.ai.QuestionAndAnswerDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * AI得分判题策略
 * @author: Guan
 **/
@ScoringStrategyConfig(appType = 1,scoringStrategy = 1)
public class AiScoreTestStrategy implements ScoringStrategy{


    @Resource
    private QuestionService questionService;


    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;



    @Override
    public UserAnswer doScore(App app, List<String> choiceList) {
        if(app == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"应用不存在");
        }
        //限流
        redisLimiterManager.doLimit(app.getUserId());
        String appName = app.getAppName();
        String appDesc = app.getAppDesc();
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appId",app.getId());
        //封装题目对象
        Question question = questionService.getOne(queryWrapper);
        String questionContentStr = question.getQuestionContent();
        List<QuestionContent> questionContentList = JSONUtil.toList(questionContentStr, QuestionContent.class);
        if(CollUtil.isEmpty(questionContentList) || CollUtil.isEmpty(choiceList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"题目或答案为空");
        }
        if(questionContentList.size() != choiceList.size()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"题目或答案数量不一致");
        }
        List<QuestionAndAnswerDTO>  questionAndAnswerDTOList = new ArrayList<>();

        for (int i = 0; i < questionContentList.size(); i++) {
            for (QuestionContentOption option : questionContentList.get(i).getOptions()) {
                QuestionAndAnswerDTO questionAndAnswerDTO = new QuestionAndAnswerDTO();
                if(option.getKey().equals(choiceList.get(i))){
                    questionAndAnswerDTO.setAnswer(option.getValue());
                    questionAndAnswerDTO.setTitle(questionContentList.get(i).getTitle());
                    continue;
                }
                questionAndAnswerDTOList.add(questionAndAnswerDTO);
                if(StringUtils.isAnyBlank(questionAndAnswerDTO.getAnswer(),questionAndAnswerDTO.getTitle())){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"选项中存在题目没有对应答案");
                }
            }
        }
        String jsonStr = JSONUtil.toJsonStr(questionAndAnswerDTOList);

        // 封装用户输入信息
        String userMessage = getUserMessage(appName,appDesc,jsonStr);
        String aiResponse = aiManager.getScoringResultByAiResponse(userMessage);
        String resultMessage = getResultMessage(aiResponse);
        AiTestResult aiTestResult = JSONUtil.toBean(resultMessage, AiTestResult.class);
        UserAnswer userAnswer = new UserAnswer();
        BeanUtils.copyProperties(aiTestResult,userAnswer);
        return userAnswer;
    }


    /**
     * 封装用户输入信息
     * @param appName 应用名称
     * @param appDesc 应用描述
     * @param jsonStr 封装好的题目 和 用户答案 的json字符串
     * @return 用户输入信息
     */
    private String getUserMessage(String appName, String appDesc, String jsonStr) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(appName).append("\n");
        stringBuilder.append("【【【").append(appDesc).append("】】】").append("\n");
        stringBuilder.append(jsonStr);
        return stringBuilder.toString();
    }


    /**
     * 封装ai返回值
     * @param aiResponse
     * @return
     */
    private String getResultMessage(String aiResponse){
        //去掉首尾 []
        int start = aiResponse.indexOf("[");
        int end = aiResponse.lastIndexOf("]");
        return aiResponse.substring(start,end + 1);
    }

}
